package com.mall.config;

import org.springframework.cache.annotation.CachingConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @Package: com.delivery.config
 * @author: xiao-chen
 * @Create: 2023/4/2-13:48
 * @Version: v 1.0
 * @Description: 配置Redis序列化
 */
@Configuration
public class RedisConfig implements CachingConfigurer {

    private static final String STANDARD_PATTERN = "yyyy/MM/dd HH:mm:ss";
    private static final String DATE_PATTERN = "yyyy/MM/dd";
    private static final String TIME_PATTERN = "HH:mm:ss";

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(connectionFactory);

        // 设置key序列化器
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());

        // 设置value序列化器
        redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<>(Object.class));
        redisTemplate.setHashValueSerializer(new Jackson2JsonRedisSerializer<>(Object.class));

        return redisTemplate;
    }

    @Bean
    public DefaultRedisScript<Long> decrScript() {
        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
        //decrement.lua脚本位置和application.yml同级目录
        redisScript.setLocation(new ClassPathResource("decrement.lua"));
        redisScript.setResultType(Long.class);
        return redisScript;
    }

    @Bean
    public DefaultRedisScript<Long> incrScript() {
        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
        //increment.lua脚本位置和application.yml同级目录
        redisScript.setLocation(new ClassPathResource("increment.lua"));
        redisScript.setResultType(Long.class);
        return redisScript;
    }

}
